﻿/*
 * Created by SharpDevelop.
 * User: StrunevskyDV
 * Date: 11.05.2010
 * Time: 18:34
 * 
 * To change this template use Tools | Options | Coding | Edit Standard Headers.
 */
using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Threading;

namespace vfw
{
	/// <summary>
	/// Description of JpegWriter.
	/// </summary>
	public class JpegWriter: IDisposable
	{
		string filePath = string.Empty;
		
		public JpegWriter(string path)
		{
			filePath=path;
			if(!System.IO.Directory.Exists(path))
				System.IO.Directory.CreateDirectory(path);
		}
		
		public void Dispose()
		{
			
		}
		
		DateTime lastSaveTime = DateTime.Now;
		
		public void  AddFrame(System.Drawing.Bitmap bmp)
		{
			//ThreadPool.QueueUserWorkItem(new WaitCallback(SaveJpegCaptureWithCurentTime),bmp);
			SaveJpegCaptureWithCurentTime(bmp);
		}

		void SaveJpegCaptureWithCurentTime(Object param)
		{
			Bitmap bmp = (Bitmap)param;
			DateTime date = DateTime.Now;
			String fileName = String.Format("\\{0}-{1}-{2} {3}-{4}-{5}-{6}.jpg", date.Year, date.Month, date.Day, date.Hour, date.Minute, date.Second, date.Millisecond);
			string subfolder =String.Format(@"\{0}-{1}-{2}\", date.Year, date.Month, date.Day);
			if(!Directory.Exists(filePath+subfolder))
			{
				Directory.CreateDirectory(filePath+subfolder);
			}
			saveJpeg(filePath+subfolder + fileName, bmp, 80);
		}
		
		public void saveJpeg(string path, Bitmap img, long quality)
		{
			// Encoder parameter for image quality
			EncoderParameter qualityParam = new EncoderParameter(Encoder.Quality, quality);

			// Jpeg image codec
			ImageCodecInfo jpegCodec = this.getEncoderInfo("image/jpeg");

			if(jpegCodec == null)
				return;

			EncoderParameters encoderParams = new EncoderParameters(1);
			encoderParams.Param[0] = qualityParam;
			
			img.Save(path, jpegCodec, encoderParams);
			img.Dispose();
		}

		private ImageCodecInfo getEncoderInfo(string mimeType)
		{
			// Get image codecs for all image formats
			ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders();

			// Find the correct image codec
			for (int i = 0; i < codecs.Length; i++)
				if (codecs[i].MimeType == mimeType)
					return codecs[i];
			return null;
		}
	}
}
